package com.sgb.kjwl.viewmodel.transport;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Point;
import android.location.LocationManager;
import android.os.Handler;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.map.MapCarInfoEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.OperateGoodsSourcePlaceVO;
import com.sgb.kjwl.model.entity.transport.common.AddressItem;
import com.swgk.core.view.entity.PermissionEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Describe:
 * Author:  yangLei
 * Date:    2021/8/13
 */
public class MapFindingCarModel extends AndroidViewModel {
    //地图缩放级别
    public float zoomLevel = 15f;
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarLen = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarFunction = new MutableLiveData<>();
    public MutableLiveData<Integer> ldCurrAddress = new MutableLiveData<>();
    public MutableLiveData<Integer> ldSearchResult = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldIsClickMarker = new MutableLiveData<>();
    public MutableLiveData<Boolean> pLd = new MutableLiveData<>();//权限
    public MutableLiveData<Boolean> ldInquiry = new MutableLiveData<>();//询价权限
    public MutableLiveData<Boolean> ldUnfold = new MutableLiveData<>();//折贴
    public String searchRadius = "0";//默认不限公里

    private List<AddressItem> addressPointList = new ArrayList<>();//地址点集合
    private List<AddressItem> bundles = new ArrayList<>();
    //货源信息标记集合
    private List<Marker> markers = new ArrayList<>();
    private List<LatLng> latLngs = new ArrayList<>();//经纬度集合
    private AMap aMap;
    private int lastPosition;
    private Marker markerLast;
    private LatLng currLatLng;//当前搜索的中心点
    private List<MapCarInfoEntity> cars = new ArrayList<>();//当前地图上展示的车辆信息集合
    //屏幕高度
    private int mScreenWidth;
    private boolean isFirst = true;//用于临时解决第一次进入该页面搜索半径问题


    //装卸点经纬度信息
    private List<LatLonPoint> sourcePoints = new ArrayList<>();
    //货源信息标记集合
    private List<MarkerOptions> markerOptions = new ArrayList<>();
    private RouteSearch planRouteSearch;
    public OperateGoodsSourcePlaceVO place;

    public MutableLiveData<Boolean> ldAddChangeListener = new MutableLiveData<>();
    private Handler mHandler = new Handler(msg -> {
        ldAddChangeListener.postValue(true);
        return false;
    });
    private Context mContext;

    public MapFindingCarModel(@NonNull @NotNull Application application) {
        super(application);
        this.mContext = application;
    }

    public AMap getAMap() {
        return aMap;
    }

    public void setAMap(AMap aMap) {
        this.aMap = aMap;
        //添加marker点击监听
        aMap.setOnMarkerClickListener(marker -> {
            if (marker.getObject() != null) {
                AddressItem item = (AddressItem) marker.getObject();
                if (item.getPosition() > 0) {
                    for (int i = 0; i < bundles.size(); i++) {
                        if (item.getPosition() == i) {
                            ldIsClickMarker.postValue(true);
                            if (bundles.get(i).isBigMarkView()) {
                                setMarkStyle(i, marker, false);
                                ldCurrAddress.postValue(null);
                            } else {
                                setMarkStyle(i, marker, true);
                                ldCurrAddress.postValue(i);
                            }
                            if (lastPosition != i) {
                                resetMarker(false);
                            }
                            markerLast = marker;
                            lastPosition = i;
                            break;
                        }
                    }
                }
            } else {
                return true;//不显示在中心
            }
            return false;
        });
    }

    public List<MapCarInfoEntity> getCars() {
        return cars;
    }

    public void setCars(List<MapCarInfoEntity> cars) {
        this.cars = cars;
    }

    public void moveMap(double lat, double lng) {
        if (aMap != null) {
            ldAddChangeListener.postValue(false);
            mHandler.removeMessages(1);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), zoomLevel));
            mHandler.sendEmptyMessageDelayed(1, 200);
        }
    }

    /**
     * 加载地图信息
     */
    public void loadMarkerInfo(List<MapCarInfoEntity> carEntities) {
        if (aMap == null || carEntities == null || carEntities.size() <= 0)
            return;
        aMap.clear();
        latLngs.clear();
        cars.clear();
        addressPointList.clear();

        if (currLatLng != null) {
            addressPointList.add(new AddressItem("", "", "",
                    R.mipmap.icon_location_blue, currLatLng.latitude, currLatLng.longitude, R.mipmap.icon_location_blue, R.mipmap.icon_location_blue));
            latLngs.add(currLatLng);
        }

        for (int i = 0; i < carEntities.size(); i++) {
            MapCarInfoEntity infoEntity = carEntities.get(i);
            if (infoEntity.getLatitude()!=null&&infoEntity.getLatitude() > 0 && infoEntity.getLongitude() > 0) {
                cars.add(infoEntity);
                latLngs.add(new LatLng(infoEntity.getLatitude(), infoEntity.getLongitude()));
                addressPointList.add(new AddressItem("", "", "",
                        R.mipmap.ic_find_car_marker_red, infoEntity.getLatitude(), infoEntity.getLongitude(), R.mipmap.ic_find_car_marker_red, R.mipmap.ic_find_car_marker_red_click));
            }
        }
        //添加所有marker
        addMarkers();
    }

    public void resetMarkersSmall() {
        if (markers != null && markers.size() > 0) {
            for (int i = 0; i < markers.size(); i++) {
                setMarkStyle(i, markers.get(i), false);
            }
        }
    }

    public void addMarkers() {
        bundles.clear();
        markers.clear();
        for (int i = 0; i < addressPointList.size(); i++) {
            AddressItem entity = addressPointList.get(i);
            entity.setPosition(i);
            bundles.add(entity);
            LatLng latLng = new LatLng(entity.getLatitude(), entity.getLongitude());
            MarkerEntity markerEntity = new MarkerEntity(latLng, entity.getMakerIcon());
            Marker marker = aMap.addMarker(getMarkerOptions(markerEntity));
            if (i != 0) {
                marker.setObject(entity);
                marker.setClickable(true);
            } else {
                marker.setClickable(false);
            }
            markers.add(marker);
        }
    }


    public MarkerOptions getMarkerOptions(MarkerEntity markerEntity) {
        BitmapDescriptor bitmapSmall;
        if (markerEntity.getIcon() == 0 && markerEntity.getView() != null) {
            bitmapSmall = BitmapDescriptorFactory.fromView(markerEntity.getView());
        } else {
            bitmapSmall = BitmapDescriptorFactory.fromResource(markerEntity.getIcon());
        }
        MarkerOptions markerOption = new MarkerOptions()
                .position(markerEntity.getLatLng())
                .title(markerEntity.getTitle())
                .icon(bitmapSmall)
                .draggable(false);
        return markerOption;
    }

    /**
     * 将视图移到定位或者装车点
     *
     * @param latLng
     */
    public void addLocationMarker(LatLng latLng) {
        if (aMap == null)
            return;
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_location_blue));
        aMap.addMarker(markerOption);
    }

    /**
     * 根据搜索条件检索车辆
     *
     * @param lat        纬度
     * @param log        经度
     * @param carTypeNos 车型No，逗号分割
     * @param carLenNos  车长No，逗号分割
     * @param functionNo 车辆功能No
     */
    public void getCarByCondition(Activity activity, double lat, double log, String carTypeNos, String carLenNos, String functionNo) {
        if (lat > 0 && log > 0) {
            currLatLng = new LatLng(lat, log);
            moveMap(lat, log);
        } else {
            return;
        }
        Map<String, Object> map = new HashMap();
        map.put("radius", searchRadius);
        map.put("searchLatitude", lat);
        map.put("searchLongitude", log);
        map.put("carTypeNos", carTypeNos);
        map.put("carLenNos", carLenNos);
        map.put("functionNos", functionNo);
        map.put("page", 1);
        map.put("limit", 200);
        map.put("needVideo", 0);
        DialogHelper.showProgressDialog(activity, "请求中...");
        NewAPIManager.getInstance().getLogisticsAPI().findCarByMap(map).enqueue(new ICallBack<BaseEntity<ProListEntity<List<MapCarInfoEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ProListEntity<List<MapCarInfoEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response == null || response.getData() == null)
                    return;
                if (response.getData().getList()!=null&&response.getData().getList().size() > 0) {
                    ldSearchResult.postValue(response.getData().getList().size());
                    loadMarkerInfo(response.getData().getList());
                } else {
                    if (aMap != null)
                        aMap.clear();
                    addLocationMarker(currLatLng);
                    ldSearchResult.postValue(0);
                }
                setPlanRouteInfo(place);
            }
        });
    }

    /**
     * 获取车型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getAllCarType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;
                if (response.body().getCode().equals("200") && response.body().getData() != null) {
                    ldCarType.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }


    /**
     * 根据车型获取车长
     */
    public void getCarLengthList(List<String> list) {
        NewAPIManager.getInstance().getLogisticsAPI().getCarLenByTypes(list).enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;
                if (response.body().getCode().equals("200") && response.body().getData() != null) {
                    ldCarLen.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }

    /**
     * 获取车辆功能列表
     */
    public void getCarFunction() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarFunction().enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                if (data.getData() == null) {
                    data.setData(new ArrayList<>());
                }
//                data.getData().add(0, new GoodsInfoTypeEntity3("", "不限"));
                ldCarFunction.postValue(data.getData());
            }
        });
    }


    //设置maker大小图标
    private void setMarkStyle(int pos, Marker marker, boolean isBigMarkView) {
        AddressItem entity = bundles.get(pos);
        BitmapDescriptor bitmapSmall = isBigMarkView ? BitmapDescriptorFactory.fromResource(entity.getBigMakerIcon()) : BitmapDescriptorFactory.fromResource(entity.getMakerIcon());
        entity.setBigMarkView(isBigMarkView);
        marker.setIcon(bitmapSmall);
    }

    public void resetMarker(boolean close) {
        if (markerLast == null)
            return;
        AddressItem entity = bundles.get(lastPosition);
        markerLast.setIcon(BitmapDescriptorFactory.fromResource(entity.getMakerIcon()));
        entity.setBigMarkView(false);
        if (close) {
            markerLast = null;
        }
    }

    /**
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    public boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * 获取屏幕中心的经纬度坐标
     *
     * @param mMapView
     * @return
     */
    public LatLng getMapCenterPoint(MapView mMapView) {
        int left = mMapView.getLeft();
        int top = mMapView.getTop();
        int right = mMapView.getRight();
        int bottom = mMapView.getBottom();
        // 获得屏幕中心点的位置
        int x = (int) (mMapView.getX() + (right - left) / 2);
        int y = (int) (mMapView.getY() + (bottom - top) / 2);
        Projection projection = mMapView.getMap().getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));
        return pt;
    }

    /**
     * 计算当前半径
     */
    private String calculateCurrentRadius() {
        if (aMap == null)
            return "1110.85";
        //计算并设置设置当前半径(单位：米)
        if (mScreenWidth == 0) {
            mScreenWidth = ScreenUtil.getDisplayWidth();
        }
        //屏幕高度的一半 * 当前缩放1px代表的米数
        String radius = NumberUtil.trim0(mScreenWidth / 2f * aMap.getScalePerPixel());
        return radius;
    }

    /**
     * 用户物流权限
     */
    public void getLogisticsPermission(Activity activity) {
        //获取用户数据
        DialogHelper.showProgressDialog(activity, "请求中...");
        NewAPIManager.getInstance().getLogisticsAPI().getLogisticsPermissions().enqueue(new ICallBack<BaseEntity<PermissionEntity>>() {
            @Override
            public void onSuccess(BaseEntity<PermissionEntity> data) {
             if(data.isSuccess()){
                 SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, data.getData().getUserType());
                 UserOperating.getInstance().setUserInfo(data.getData());
                 pLd.postValue(true);
             }
            }
        });
    }


    /**
     * 预置路径信息
     */
    public void setPlanRouteInfo(OperateGoodsSourcePlaceVO place) {
        //装载 装卸地经纬度
        if (place != null && place.getDestLatitude() != 0 && place.getDestLongitude() != 0) {
            this.place = place;
            aMap.clear();
            addMarkers();
            markerOptions.clear();
            LatLonPoint sendPoint = null;
            LatLng sendLL = null;
            if (place.getLatitude() > 0 && place.getLongitude() > 0) {
                sendPoint = new LatLonPoint(place.getLatitude(), place.getLongitude());
                sendLL = new LatLng(place.getLatitude(), place.getLongitude());
            }

            LatLonPoint destPoint = null;
            LatLng destLL = null;
            if (place.getDestLatitude() > 0 && place.getDestLongitude() > 0) {
                destPoint = new LatLonPoint(place.getDestLatitude(), place.getDestLongitude());
                destLL = new LatLng(place.getDestLatitude(), place.getDestLongitude());
            }

            sourcePoints.clear();
            sourcePoints.add(sendPoint);
            sourcePoints.add(destPoint);

            //起点
            markerOptions.add(createMarker(sendLL, 1));
            //终点
            markerOptions.add(createMarker(destLL, 2));
            planningLoadingRoute(sourcePoints, 1);
        }
    }


    /**
     * 添加需要规划的路线数据，并开启异步查询
     *
     * @param points 路线连接点
     * @param type   规划路线的类型：1——计划，2——实际
     */
    public void planningLoadingRoute(List<LatLonPoint> points, int type) {
        //路线点不能少于两个
        if (points == null || points.size() < 2) {
            return;
        }
        List<LatLonPoint> passedByPoints = null;
        //设置开始位置坐标点(注意经纬度不能写反,会报错1800(只能规划到中国区域里的地图路线))
        LatLonPoint startPoint = points.get(0);
        //设置目的地坐标点
        LatLonPoint endPoint = points.get(points.size() - 1);
        //查询信息对象
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);

        if (points.size() > 2) {
            passedByPoints = new ArrayList<>();
            for (int i = 1; i < points.size() - 1; i++) {
                passedByPoints.add(points.get(i));
            }
        }
        //设置搜索参数 1.fromAndTo 路径的起点终点  2.路径规划的策略（可选），默认为“躲避拥堵” 3.途经点，可选 4.避让区域，可选， 5.货车大小 ,默认轻型车
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
                fromAndTo,
                RouteSearch.DRIVING_SINGLE_SHORTEST,
                passedByPoints,
                null,
                "");

        if (type == 1) {
            if (planRouteSearch == null)
                planRouteSearch = new RouteSearch(mContext);
            // 搜索监听
            planRouteSearch.setRouteSearchListener(new OnPlanListener());
            //开始异步查询
            planRouteSearch.calculateDriveRouteAsyn(query);
        }
    }


    /**
     * 路线规划回调类
     */
    private class OnPlanListener implements RouteSearch.OnRouteSearchListener {

        @Override
        public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

        }

        @Override
        public void onDriveRouteSearched(DriveRouteResult result, int code) {
            if (code == 1000 && result != null && result.getPaths() != null && result.getPaths().size() > 0) {
                if (aMap == null) {
                    return;
                }

                List<DrivePath> paths = result.getPaths();
                //创建存储坐标点的集合
                List<LatLonPoint> latLonPoints = new ArrayList<>();
                List<LatLng> planLatLngs = new ArrayList<>();

                //遍历获取规划的所有路线坐标点
                for (DriveStep mDriveStep : paths.get(0).getSteps()) {
                    for (LatLonPoint mLatLonPoint : mDriveStep.getPolyline()) {
                        latLonPoints.add(mLatLonPoint);
                        latLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                        planLatLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                    }
                }

                //无纹理纯色路线
//                DrivePath drivePath = paths.get(0);
//                PlanRouteOverlay overlay = new PlanRouteOverlay(context, aMap, drivePath,
//                        result.getStartPos(), result.getTargetPos(), latLonPoints);
//                overlay.setThroughPointIconVisibility(false);//隐藏途径点
//                overlay.setNodeIconVisibility(false);//设置节点marker是否显示
//                overlay.setIsColorfulline(false);//是否用颜色展示交通拥堵情况，默认true
//                overlay.addToMap();
//                overlay.zoomToSpan();

                //带纹理纯色路线
                aMap.addPolyline(new PolylineOptions()
                        //路线坐标点的集合
                        .addAll(planLatLngs)
                        //线的宽度
                        .width(20)
                        .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.map_alr))
                );
                ldUnfold.postValue(true);

                //添加所有marker
                for (MarkerOptions sourceMarker : markerOptions) {
                    aMap.addMarker(sourceMarker);
                }

                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds(
                        new LatLng(result.getStartPos().getLatitude(), result.getStartPos().getLongitude()),
                        new LatLng(result.getTargetPos().getLatitude(), result.getTargetPos().getLongitude())), 50));
            } else {
                MLog.d("api", "路线规划失败");
            }
        }

        @Override
        public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

        }

        @Override
        public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

        }
    }


    private MarkerOptions createMarker(LatLng latLng, int type) {
        int resource = 0;
        switch (type) {
            case 1:
                resource = R.mipmap.icon_samll_handle;
                break;
            case 2:
                resource = R.mipmap.icon_unload;
                break;
        }
        BitmapDescriptor markIcon = BitmapDescriptorFactory.fromResource(resource);
        return new MarkerOptions().position(latLng).icon(markIcon);
    }

    /**
     * 查询询价权限
     *
     * @param carNo
     */
    public void getInquiryPermissions(String carNo) {
        if (!TextUtils.isEmpty(carNo)) {
            NewAPIManager.getInstance().getLogisticsAPI().getInquiryPermissions(carNo, "").enqueue(new ICallBack<BaseEntity<Boolean>>() {
                @Override
                public void onSuccess(BaseEntity<Boolean> data) {
                    if (data.isSuccess()) {
                        ldInquiry.postValue(data.getData());
                    }
                }
            });
        }
    }
}
